package com.rymcu.forest.auth;

import com.alibaba.fastjson2.JSONObject;
import com.rymcu.forest.core.result.GlobalResult;
import com.rymcu.forest.core.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * JWT Authentication Filter for Spring Security 6
 *
 * @author ronger
 */
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    private final AuthenticationManager authenticationManager;

    public JwtFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            String token = extractToken(request);

            if (StringUtils.isNotBlank(token)) {
                // 创建未认证的JWT token
                JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(token);

                // 进行认证
                Authentication authentication = authenticationManager.authenticate(authenticationToken);

                // 将认证结果设置到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        } catch (AuthenticationException e) {
            log.error("JWT authentication failed: {}", e.getMessage());
            SecurityContextHolder.clearContext();
            sendAuthenticationError(response, e);
            return;
        } catch (Exception e) {
            log.error("Error during JWT processing: {}", e.getMessage(), e);
            SecurityContextHolder.clearContext();
            sendInternalServerError(response);
            return;
        }

        filterChain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        // 尝试从Authorization头获取token
        String bearerToken = request.getHeader(JwtConstants.AUTHORIZATION);
        if (StringUtils.isNotBlank(bearerToken)) {
            // 支持Bearer token格式
            if (bearerToken.startsWith("Bearer ")) {
                return bearerToken.substring(7);
            }
            return bearerToken;
        }

        // 尝试从X-Upload-Token头获取token（编辑器上传文件使用）
        String uploadToken = request.getHeader(JwtConstants.UPLOAD_TOKEN);
        if (StringUtils.isNotBlank(uploadToken)) {
            return uploadToken;
        }

        return null;
    }

    private void sendAuthenticationError(HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        GlobalResult<?> errorResult = new GlobalResult<>(ResultCode.UNAUTHENTICATED);
        String jsonResponse = JSONObject.toJSONString(errorResult);

        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }

    private void sendInternalServerError(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        GlobalResult<?> errorResult = new GlobalResult<>(ResultCode.ERROR);
        String jsonResponse = JSONObject.toJSONString(errorResult);

        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        log.debug("JWT filter checking path: {}", path);
        // 不需要JWT验证的路径（考虑context-path）
        boolean shouldNotFilter = path.startsWith("/api/console/")
                || path.startsWith("/api/v1/console/")
                || path.startsWith("/auth/")
                || path.startsWith("/public/")
                || path.startsWith("/static/")
                || path.startsWith("/css/")
                || path.startsWith("/js/")
                || path.startsWith("/images/")
                || path.startsWith("/favicon.ico")
                || path.equals("/")
                || path.startsWith("/actuator/");
        log.debug("JWT filter shouldNotFilter for path {}: {}", path, shouldNotFilter);
        return shouldNotFilter;
    }
}